import axios from 'axios';
import { 
  Project, 
  ProjectCreate, 
  ProjectUpdate, 
  ParameterCategory, 
  ParameterCategoryCreate, 
  ParameterCategoryUpdate,
  Parameter,
  ParameterCreate,
  ParameterUpdate,
  ParameterValue,
  ParameterValueCreate,
  ParameterValueUpdate,
  ApiResponse,
  MessageResponse,
  ExportFormat,
  ImportFormat,
  ExperimentRun,
  ExperimentFullData
} from '../types';

// 检测是否在Electron环境中
const isElectron = window.navigator.userAgent.toLowerCase().indexOf('electron') > -1;

// 创建axios实例（优先读取运行时配置 window.__API_BASE__，其次读取构建时环境变量，默认 '/api'）
const runtimeApiBase = (window as any).__API_BASE__;
const buildTimeApiBase = process.env.REACT_APP_API_BASE;
const resolvedBaseURL = (runtimeApiBase || buildTimeApiBase || '/api') as string;

const api = axios.create({
  baseURL: resolvedBaseURL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器 - 添加token
api.interceptors.request.use(
  (config) => {
    // 获取token并添加到请求头
    const token = localStorage.getItem('auth_token');
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    
    console.log('🚀 API Request:', {
      method: config.method?.toUpperCase(),
      url: config.url,
      data: config.data,
      params: config.params
    });
    return config;
  },
  (error) => {
    console.error('❌ Request Error:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    console.log('✅ API Response:', {
      status: response.status,
      url: response.config.url,
      data: response.data
    });
    return response.data;
  },
  (error) => {
    console.error('❌ API Error:', {
      status: error.response?.status,
      url: error.config?.url,
      message: error.message,
      data: error.response?.data
    });
    return Promise.reject(error);
  }
);

// 项目相关API
export const projectApi = {
  // 获取项目列表
  getProjects: (): Promise<Project[]> => {
    return api.get('/projects/');
  },

  // 上传导入
  importByUpload: async (file: File, format: string): Promise<MessageResponse> => {
    // 直接使用原始字节上传
    const ab = await file.arrayBuffer();
    return axios.post(`${api.defaults.baseURL}/import/upload/${format}`, ab, {
      headers: { 'Content-Type': 'application/octet-stream', 'X-Filename': file.name },
      transformRequest: [(data) => data],
      onUploadProgress: (e) => console.log('upload progress', e.loaded, e.total)
    }).then(r => r.data);
  },

  // 获取项目详情
  getProject: (id: number): Promise<Project> => {
    return api.get(`/projects/${id}/`);
  },

  // 通过英文名称获取项目详情
  getProjectByName: (nameEn: string): Promise<Project> => {
    return api.get(`/projects/${nameEn}`);
  },

  // 获取导出格式
  getExportFormats: (): Promise<{ formats: ExportFormat[] }> => {
    return api.get(`/export/formats`);
  },

  // 获取导入格式
  getImportFormats: (): Promise<{ formats: ImportFormat[] }> => {
    return api.get(`/import/formats`);
  },

  // 触发导出并下载（返回blob）
  exportProject: async (projectNameEn: string, format: string): Promise<Blob> => {
    const url = `${api.defaults.baseURL}/projects/${projectNameEn}/export/${format}`;
    const resp = await axios.post(url, null, { responseType: 'blob' });
    return resp.data as Blob;
  },

  // 创建项目
  createProject: (data: ProjectCreate): Promise<Project> => {
    return api.post('/projects/', data);
  },

  // 更新项目
  updateProject: (id: number, data: ProjectUpdate): Promise<Project> => {
    return api.put(`/projects/${id}/`, data);
  },

  // 通过英文名称更新项目
  updateProjectByName: (nameEn: string, data: ProjectUpdate): Promise<Project> => {
    return api.put(`/projects/${nameEn}`, data);
  },

  // 通过英文名称更新项目年份区间
  updateProjectYearRangeByName: (
    nameEn: string,
    data: { start_year: number; end_year: number; year_step: number }
  ): Promise<Project> => {
    return api.put(`/projects/${nameEn}/year-range`, data);
  },

  // 删除项目
  deleteProject: (id: number): Promise<MessageResponse> => {
    return api.delete(`/projects/${id}/`);
  },

  // 通过英文名称删除项目
  deleteProjectByName: (nameEn: string): Promise<MessageResponse> => {
    return api.delete(`/projects/${nameEn}`);
  },

  // 获取项目的详细参数信息（一次性获取所有分类、参数及其值）
  // 使用 JSON 导出接口获取数据
  getProjectDetailed: async (nameEn: string): Promise<any> => {
    const url = `${api.defaults.baseURL}/projects/${nameEn}/export/json`;
    const resp = await axios.post(url, null);
    return resp.data;
  },
};

// 参数分类相关API
export const categoryApi = {
  // 获取项目的参数分类列表
  getCategories: (projectId: number): Promise<ParameterCategory[]> => {
    return api.get(`/projects/${projectId}/categories/`);
  },

  // 通过项目英文名称获取参数分类列表
  getCategoriesByName: (projectNameEn: string): Promise<ParameterCategory[]> => {
    return api.get(`/projects/${projectNameEn}/categories`);
  },

  // 获取参数分类详情
  getCategory: (projectId: number, categoryId: number): Promise<ParameterCategory> => {
    return api.get(`/projects/${projectId}/categories/${categoryId}/`);
  },

  // 创建参数分类
  createCategory: (projectId: number, data: ParameterCategoryCreate): Promise<ParameterCategory> => {
    return api.post(`/projects/${projectId}/categories/`, data);
  },

  // 通过项目英文名称创建参数分类
  createCategoryByName: (projectNameEn: string, data: ParameterCategoryCreate): Promise<ParameterCategory> => {
    return api.post(`/projects/${projectNameEn}/categories`, data);
  },

  // 更新参数分类
  updateCategory: (projectId: number, categoryId: number, data: ParameterCategoryUpdate): Promise<ParameterCategory> => {
    return api.put(`/projects/${projectId}/categories/${categoryId}/`, data);
  },

  // 通过英文名称更新参数分类
  updateCategoryByName: (projectNameEn: string, categoryNameEn: string, data: ParameterCategoryUpdate): Promise<ParameterCategory> => {
    return api.put(`/projects/${projectNameEn}/categories/${categoryNameEn}`, data);
  },

  // 删除参数分类
  deleteCategory: (projectId: number, categoryId: number): Promise<MessageResponse> => {
    return api.delete(`/projects/${projectId}/categories/${categoryId}/`);
  },

  // 通过英文名称删除参数分类
  deleteCategoryByName: (projectNameEn: string, categoryNameEn: string): Promise<MessageResponse> => {
    return api.delete(`/projects/${projectNameEn}/categories/${categoryNameEn}`);
  },
};

// 参数相关API
export const parameterApi = {
  // 获取分类的参数列表
  getParameters: (projectId: number, categoryId: number): Promise<Parameter[]> => {
    return api.get(`/projects/${projectId}/categories/${categoryId}/parameters/`);
  },

  // 获取分类的参数列表（使用英文名称）
  getParametersByName: (projectNameEn: string, categoryNameEn: string): Promise<Parameter[]> => {
    return api.get(`/projects/${projectNameEn}/categories/${categoryNameEn}/parameters`);
  },

  // 获取参数详情
  getParameter: (projectId: number, categoryId: number, parameterId: number): Promise<Parameter> => {
    return api.get(`/projects/${projectId}/categories/${categoryId}/parameters/${parameterId}/`);
  },

  // 创建参数
  createParameter: (projectId: number, categoryId: number, data: ParameterCreate): Promise<Parameter> => {
    return api.post(`/projects/${projectId}/categories/${categoryId}/parameters/`, data);
  },

  // 创建参数（使用英文名称）
  createParameterByName: (projectNameEn: string, categoryNameEn: string, data: ParameterCreate): Promise<Parameter> => {
    return api.post(`/projects/${projectNameEn}/categories/${categoryNameEn}/parameters`, data);
  },

  // 更新参数
  updateParameter: (projectId: number, categoryId: number, parameterId: number, data: ParameterUpdate): Promise<Parameter> => {
    return api.put(`/projects/${projectId}/categories/${categoryId}/parameters/${parameterId}/`, data);
  },

  // 更新参数（使用英文名称）
  updateParameterByName: (projectNameEn: string, categoryNameEn: string, parameterNameEn: string, data: ParameterUpdate): Promise<Parameter> => {
    return api.put(`/projects/${projectNameEn}/categories/${categoryNameEn}/parameters/${parameterNameEn}`, data);
  },

  // 删除参数
  deleteParameter: (projectId: number, categoryId: number, parameterId: number): Promise<MessageResponse> => {
    return api.delete(`/projects/${projectId}/categories/${categoryId}/parameters/${parameterId}/`);
  },

  // 通过英文名称删除参数
  deleteParameterByName: (projectNameEn: string, categoryNameEn: string, parameterNameEn: string): Promise<MessageResponse> => {
    return api.delete(`/projects/${projectNameEn}/categories/${categoryNameEn}/parameters/${parameterNameEn}`);
  },
};

// 参数值相关API
export const parameterValueApi = {
  // 获取参数的值列表
  getParameterValues: (projectId: number, categoryId: number, parameterId: number): Promise<ParameterValue[]> => {
    return api.get(`/projects/${projectId}/categories/${categoryId}/parameters/${parameterId}/values/`);
  },

  // 获取参数的值列表（使用英文名称）
  getParameterValuesByName: (projectNameEn: string, categoryNameEn: string, parameterNameEn: string): Promise<ParameterValue[]> => {
    return api.get(`/projects/${projectNameEn}/categories/${categoryNameEn}/parameters/${parameterNameEn}/values`);
  },

  // 创建参数值
  createParameterValue: (projectId: number, categoryId: number, parameterId: number, data: ParameterValueCreate): Promise<ParameterValue> => {
    return api.post(`/projects/${projectId}/categories/${categoryId}/parameters/${parameterId}/values/`, data);
  },

  // 创建参数值（使用英文名称）
  createParameterValueByName: (projectNameEn: string, categoryNameEn: string, parameterNameEn: string, data: ParameterValueCreate): Promise<ParameterValue> => {
    return api.post(`/projects/${projectNameEn}/categories/${categoryNameEn}/parameters/${parameterNameEn}/values`, data);
  },

  // 更新参数值
  updateParameterValue: (projectId: number, categoryId: number, parameterId: number, valueId: number, data: ParameterValueUpdate): Promise<ParameterValue> => {
    return api.put(`/projects/${projectId}/categories/${categoryId}/parameters/${parameterId}/values/${valueId}/`, data);
  },

  // 删除参数值
  deleteParameterValue: (projectId: number, categoryId: number, parameterId: number, valueId: number): Promise<MessageResponse> => {
    return api.delete(`/projects/${projectId}/categories/${categoryId}/parameters/${parameterId}/values/${valueId}/`);
  },

  // 批量设置参数值
  setParameterValues: (projectId: number, categoryId: number, parameterId: number, values: string[]): Promise<MessageResponse> => {
    return api.post(`/projects/${projectId}/categories/${categoryId}/parameters/${parameterId}/values/batch/`, { values });
  },

  // 批量设置参数值（使用英文名称）
  setParameterValuesByName: (projectNameEn: string, categoryNameEn: string, parameterNameEn: string, values: string[]): Promise<MessageResponse> => {
    return api.post(`/projects/${projectNameEn}/categories/${categoryNameEn}/parameters/${parameterNameEn}/values/batch`, { values });
  },
};

// 认证相关API
export const authApi = {
  // 登录
  login: (password: string): Promise<{ token: string; message: string }> => {
    return api.post('/auth/login', { password });
  },

  // 验证token
  verifyToken: (): Promise<{ valid: boolean; user: any }> => {
    return api.get('/auth/verify');
  },
};

// 实验相关API
export const experimentApi = {
  // 获取项目的实验列表
  getExperiments: (projectNameEn: string, skip: number = 0, limit: number = 100): Promise<ExperimentRun[]> => {
    return api.get(`/projects/${projectNameEn}/experiments`, { params: { skip, limit } });
  },

  // 获取实验的完整数据
  getExperimentDetail: (projectNameEn: string, experimentId: number): Promise<ExperimentFullData> => {
    return api.get(`/projects/${projectNameEn}/experiments/${experimentId}`);
  },

  // 获取序列数据内容
  getSeriesData: (
    projectNameEn: string, 
    experimentId: number, 
    seriesId: number, 
    skip: number = 0, 
    limit: number = 100
  ): Promise<{
    series_id: number;
    series_name: string;
    columns: Array<{ name: string; type: string }>;
    total_rows: number;
    skip: number;
    limit: number;
    data: any[];
    has_more: boolean;
  }> => {
    return api.get(
      `/projects/${projectNameEn}/experiments/${experimentId}/series/${seriesId}/data`, 
      { params: { skip, limit } }
    );
  },

  // 更新实验基础信息
  updateExperiment: (
    projectNameEn: string,
    experimentId: number,
    data: { name?: string; description?: string }
  ): Promise<ExperimentRun> => {
    return api.put(`/projects/${projectNameEn}/experiments/${experimentId}`, data);
  },

  // 删除实验
  deleteExperiment: (projectNameEn: string, experimentId: number): Promise<MessageResponse> => {
    return api.delete(`/projects/${projectNameEn}/experiments/${experimentId}`);
  },

  // 获取实验快照文件内容（输入参数）
  getExperimentSnapshot: (projectNameEn: string, experimentId: number): Promise<any> => {
    return api.get(`/projects/${projectNameEn}/experiments/${experimentId}/snapshot`);
  },

  // 下载实验快照文件（支持格式转换）
  downloadExperimentSnapshot: (projectNameEn: string, experimentId: number, format: string = 'json'): void => {
    const url = `/projects/${projectNameEn}/experiments/${experimentId}/snapshot/download?format=${format}`;
    // 使用完整URL触发下载
    const fullUrl = api.defaults.baseURL ? `${api.defaults.baseURL}${url}` : url;
    const link = document.createElement('a');
    link.href = fullUrl;
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  },

  // 下载实验结果Excel
  downloadExperimentResultsExcel: (projectNameEn: string, experimentId: number): void => {
    const url = `/projects/${projectNameEn}/experiments/${experimentId}/results/export/excel`;
    const fullUrl = api.defaults.baseURL ? `${api.defaults.baseURL}${url}` : url;
    const link = document.createElement('a');
    link.href = fullUrl;
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  },

  // 获取支持的导出格式列表
  getSnapshotExportFormats: (projectNameEn: string, experimentId: number): Promise<{ formats: Array<{ format: string; name: string; extensions: string[]; description: string }> }> => {
    return api.get(`/projects/${projectNameEn}/experiments/${experimentId}/snapshot/formats`);
  },
};

export default api;
